package com.eneat.smartrule.repository.impl;

import com.eneat.smartrule.mapper.RuleExecutionRecordMapper;
import com.eneat.smartrule.model.Rule;
import com.eneat.smartrule.model.RuleExecutionRecord;
import com.eneat.smartrule.repository.RuleExecutionRecordRepo;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.Map;

@Repository
public class RuleExecutionRecordRepoImpl implements RuleExecutionRecordRepo {

    @Autowired
    private RuleExecutionRecordMapper ruleExecutionRecordMapper;
    @Override
    public void saveExecutionRecord(Rule rule, Object executionResult, Map<String, Object> parameters) {

        RuleExecutionRecord ruleExecutionRecord = new RuleExecutionRecord();
        ruleExecutionRecord.setRuleId(rule.getId());
        ruleExecutionRecord.setRuleName(rule.getName());
        ObjectMapper objectMapper = new ObjectMapper();
        String inputEnv;
        try {
            inputEnv= objectMapper.writeValueAsString(parameters);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        ruleExecutionRecord.setInputEnv(inputEnv);
        ruleExecutionRecord.setExpression(rule.getExpression());
        ruleExecutionRecord.setResult(executionResult.toString());
        ruleExecutionRecordMapper.insert(ruleExecutionRecord);
    }
}
